enum DateFormat { ymd_hms, ymd_hm, ymd, hms, hm, ms }

class DatetimeUtil {
  static String _b0(int v, {int n = 10}) {
    String s = "";
    for (var i = 0; i < n ~/ 10; i++) {
      s = s + "0";
    }
    return v < n ? "$s$v" : v.toString();
  }

  // 时间格式化：DateTime转String
  static String datetimeToString(DateTime dateTime,
      {String ymdSep = "-",
      String hmsSep = ":",
      DateFormat format = DateFormat.ymd_hms}) {
    if (dateTime == null) {
      return "";
    }
    String datetimeString = "";
    String year = dateTime.year.toString();
    String month = _b0(dateTime.month);
    String day = _b0(dateTime.day);
    String hour = _b0(dateTime.hour);
    String minute = _b0(dateTime.minute);
    String second = _b0(dateTime.second);
    switch (format) {
      case DateFormat.ymd_hms:
        datetimeString =
            "$year$ymdSep$month$ymdSep$day $hour$hmsSep$minute$hmsSep$second";
        break;
      case DateFormat.ymd_hm:
        datetimeString = "$year$ymdSep$month$ymdSep$day $hour$hmsSep$minute";
        break;
      case DateFormat.ymd:
        datetimeString = "$year$ymdSep$month$ymdSep$day";
        break;
      case DateFormat.hms:
        datetimeString = "$hour$hmsSep$minute$hmsSep$second";
        break;
      case DateFormat.hm:
        datetimeString = "$hour$hmsSep$minute";
        break;
      case DateFormat.ms:
        datetimeString = "$minute$hmsSep$second";
        break;
      default:
    }
    return datetimeString;
  }

  /// 是否是今天：DateTime或String
  static bool isToday({DateTime dateTime, String dateTimeStr}) {
    if (dateTime == null && dateTimeStr == null) {
      return false;
    }
    String date1 = dateTime == null
        ? datetimeToString(DateTime.parse(dateTimeStr), format: DateFormat.ymd)
        : datetimeToString(dateTime, format: DateFormat.ymd);
    String date2 = datetimeToString(DateTime.now(), format: DateFormat.ymd);
    return date1 == date2;
  }
}
